package com.amin.concurrent;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 栅栏：管理线程的执行
 * 让它所管理的所有线程都执行到await代码行
 * @author Administrator
 *
 */
public class CyclicBarrierDemo {

	public static void main(String[] args) {
		CyclicBarrier cb = new CyclicBarrier(2);
		new Thread(new HourseRun1(cb)).start();
		new Thread(new HourseRun2(cb)).start();
	}

}

class HourseRun1 implements Runnable{
	private CyclicBarrier cd;
	
	public HourseRun1(CyclicBarrier cd) {
		super();
		this.cd = cd;
	}

	public void run() {
		try {
			System.out.println("马一来到了栅栏前");
			cd.await();//将计数器减一，产生阻塞，栅栏管理的所有线程都执行await方法之后，再释放
			System.out.println("马一开始比赛");
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (BrokenBarrierException e) {
			e.printStackTrace();
		}
	}
}
class HourseRun2 implements Runnable{
	private CyclicBarrier cd;
	
	public HourseRun2(CyclicBarrier cd) {
		super();
		this.cd = cd;
	}

	public void run() {
		try {
			System.out.println("马二玩耍中~~~");
			Thread.sleep(3000);
			System.out.println("马二来到了栅栏前");
			cd.await();
			System.out.println("马二开始比赛");
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (BrokenBarrierException e) {
			e.printStackTrace();
		}
	}
}
